package com.chartHandle.dubbo.filter;

import com.alibaba.dubbo.rpc.*;
import com.chartHandle.config.ConfigRead;
import com.chartHandle.util.SpringContextUtil;
import com.projectCommon.bean.DubboInfoContext;
import com.projectCommon.util.commonUtil.SerializationUtil;
import com.projectCommon.util.springUtil.annotation.LogInitContext;
import com.projectCommon.util.threadSave.DubboInfoContextInfoThreadHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2024/12/01/9:02
 * @target 心若有所向往，何惧道阻且长
 */
@Slf4j
@Component
@LogInitContext
public class BaseFilter implements Filter {
    @Autowired
    private ConfigRead configRead;
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (configRead == null) {
            configRead = SpringContextUtil.getBean(ConfigRead.class);
        }
        String dubboInfoContext = RpcContext.getContext().getAttachment("dubboInfoContext");
        if (dubboInfoContext == null) {
            return null;
        }
        DubboInfoContext dubboInfoContextObj = SerializationUtil.deserialize(dubboInfoContext);
        DubboInfoContextInfoThreadHolder.set(dubboInfoContextObj);
        log.info("{}-{} -- {}-{} invoke {} interface start",
                dubboInfoContextObj.getTraceId(),
                configRead.getApplicationName(),
                dubboInfoContextObj.getConsumer(),
                dubboInfoContextObj.getUserID(),
                invocation.getMethodName()
                );
        // 执行服务调用
        Result result = invoker.invoke(invocation);

        // 服务调用后输出日志
        log.info("{}-{} -- {}-{} invoke {} interface end, result:{}",
                dubboInfoContextObj.getTraceId(),
                configRead.getApplicationName(),
                dubboInfoContextObj.getConsumer(),
                dubboInfoContextObj.getUserID(),
                invocation.getMethodName(),
                "success");
        DubboInfoContextInfoThreadHolder.remove();
        return result;
    }
}
